package com.sanploy.fed.push.service.impl;

import com.sanploy.fed.push.bean.FileInfomation;
import com.sanploy.fed.push.dao.FileInfomationDao;
import com.sanploy.fed.push.service.FileService;
import com.sanploy.fed.push.util.DateUtil;
import com.sanploy.fed.push.util.FileTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/8/15.
 */
//TODO 优化此部分代码
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileInfomationDao fileInfomationDao;

    @Override
    public String savePhoto(MultipartFile file, String introduce, String url,String type,String filetype) {
        return uploadPhoto(file, introduce, url,type,filetype);
    }

    @Override
    public void saveVideo(MultipartFile file, String introduce, String url,String filetype) {
        uploadVideo(file, introduce, url,filetype);

    }

    @Override
    public List<FileInfomation> getFileByTypeAndPage(String type, int count, int page) {
        int start = (page-1)*count;
        int end = count;
        return fileInfomationDao.findByTypeOrdertimeLimit(type,start,end);
    }

    @Override
    public Long getCountByType(String type) {
        return fileInfomationDao.findCountByType(type);
    }

    @Override
    public FileInfomation findById(Long id) {
        return fileInfomationDao.findOne(id);
    }

    @Override
    public void deleteFile(Long id) {
        fileInfomationDao.delete(id);
    }


    private ExecutorService e = new ThreadPoolExecutor(3, 10, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public void uploadVideo(final MultipartFile file, final String introduce, final String url,final String filetype) {

                saveFile(file, "video", introduce, url,filetype);
    }

    public String uploadPhoto(final MultipartFile file, String introduce, String url,String type,String filetype) {
        return saveFile(file, type, introduce, url,filetype);
    }

    private String saveFile(MultipartFile file, String foldName, String introduce, String url,String filetype) {

        checksize(file);
        String suffix =  getsuffix(file,filetype);
        String uuid = UUID.randomUUID().toString();
        String fold = creatfold(foldName);
        return creatAndSave(file,fold,uuid,suffix
                ,introduce,url,foldName);
    }

    private String creatAndSave(MultipartFile file,String fold,String uuid,String suffix
    ,String introduce,String url, String foldName) {
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
            if (fold.startsWith("file")) {
                fold = fold.substring(6);
            }
            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(fold, uuid + "." + suffix)));
            stream.write(bytes);
            stream.close();

            FileInfomation fileInfomation = new FileInfomation();
            fileInfomation.setOpetime(DateUtil.getTimeNormal());
            fileInfomation.setIntroduce(introduce);
            fileInfomation.setUrl(url);
            fileInfomation.setFilename(uuid + "." + suffix);
            fileInfomation.setFilepath("/resource" + "/" + foldName + "/" + uuid + "." + suffix);
            fileInfomation.setFiletype(foldName);
            fileInfomation.setOldname(file.getOriginalFilename());
            fileInfomationDao.save(fileInfomation);
            return "/resource" + "/" + foldName + "/" + uuid + "." + suffix;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    private String creatfold(String foldName) {
        String s = FileTest.getJarDir();
        if (s.startsWith("file")) {
            s = FileTest.getJarDir().substring(6);
        }
        File file1 = new File(s+File.separator+"resource" + File.separator + foldName);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        return file1.getAbsolutePath();
    }

    private String getsuffix(MultipartFile file,String filetype) {
        String suffix = "";
        if (filetype.equals("no")){
            String x = file.getOriginalFilename();
            String[] strings = x.split("\\.");
            System.out.println(strings.length-1);
            suffix = strings[strings.length-1];
            if (x.equals("")){
                suffix = "jpg";
            }
        }else {
            suffix =filetype;
        }
        return suffix;
    }

    private void checksize(MultipartFile file) {
        if (file.getSize() ==0){
            int x = 1/0;  //抛出异常
        }
    }


}
